package com.movie.controller;

import com.movie.dto.ResponseDTO;
import com.movie.entity.User;
import com.movie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    // 登录接口
    @PostMapping("/login")
    public ResponseDTO<UserLoginResponse> login(@RequestBody UserLoginRequest request) {
        try {
            User user = userService.login(request.getUsername(), request.getPassword());
            if (user != null) {
                UserLoginResponse resp = new UserLoginResponse();
                resp.setId(user.getId());
                resp.setUsername(user.getUsername());
                resp.setToken(""); // 可以生成 JWT 或其他 token
                return ResponseDTO.success(resp, "登录成功");
            } else {
                return ResponseDTO.error("用户名或密码错误");
            }
        } catch (Exception e) {
            return ResponseDTO.error("登录失败：" + e.getMessage());
        }
    }

    // 注册接口
    @PostMapping("/register")
    public ResponseDTO<UserLoginResponse> register(@RequestBody UserLoginRequest request) {
        try {
            User user = userService.register(request.getUsername(), request.getPassword());
            if (user != null) {
                UserLoginResponse resp = new UserLoginResponse();
                resp.setId(user.getId());
                resp.setUsername(user.getUsername());
                resp.setToken("");
                return ResponseDTO.success(resp, "注册成功");
            } else {
                return ResponseDTO.error("注册失败，用户名可能已存在");
            }
        } catch (Exception e) {
            return ResponseDTO.error("注册异常：" + e.getMessage());
        }
    }
}

// 请求 DTO
class UserLoginRequest {
    private String username;
    private String password;

    public String getUsername() { return username; }
    public void setUsername(String username) { this.username = username; }
    public String getPassword() { return password; }
    public void setPassword(String password) { this.password = password; }
}

// 返回 DTO
class UserLoginResponse {
    private Integer id;
    private String username;
    private String token;

    public Integer getId() { return id; }
    public void setId(Integer id) { this.id = id; }
    public String getUsername() { return username; }
    public void setUsername(String username) { this.username = username; }
    public String getToken() { return token; }
    public void setToken(String token) { this.token = token; }
}
